﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.RoleMenu;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.RoleMenu
{
    public class recursionCommandHarder : IRequestHandler<recursionCommand, APIResult<List<DgDto>>>
    {
        private readonly IMapper mapper;
        private readonly IBaseRepository<Menu> baseRepository;

        public recursionCommandHarder(IMapper mapper, IBaseRepository<Menu> baseRepository)
        {
            this.mapper = mapper;
            this.baseRepository = baseRepository;
        }

        public Task<APIResult<List<DgDto>>> Handle(recursionCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<DgDto>> result = new APIResult<List<DgDto>>();
            result.Code = APIEnum.查询成功;
            result.Msg = APIEnum.查询成功.ToString();
            result.data = GetTree(0);
            return Task.FromResult(result);
        }

        private List<DgDto> GetTree(int MenuId)
        {
            var depaers = baseRepository.GetAll().Result.Where(x => x.PId == MenuId);
            var dtos=mapper.Map<List<DgDto>>(depaers);
            foreach (var d in dtos)
            {
                d.dgDtos = GetTree(d.MenuId);
            }
            return dtos;


        }
    }
}
